<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <el-link type="primary" :underline="false" @click="handleRegister">立即注册</el-link>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { authService } from '../services/authService'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store'

const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 表单引用
const loginFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) {
    ElMessage.error('表单未初始化')
    return
  }
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    // 调用登录接口
    const result = await authService.login(loginForm)
    
    if (result && result.token) {
      // 保存登录结果到store
      const userStore = useUserStore()
      userStore.saveLoginResult(result)
      
      // 如果选择了记住我，保存用户名
      if (loginForm.rememberMe) {
        localStorage.setItem('username', loginForm.username)
      } else {
        localStorage.removeItem('username')
      }
      
      ElMessage.success('登录成功')
      
      // 检查是否有待提交的订单数据
      const pendingOrderData = localStorage.getItem('pendingOrderData')
      if (pendingOrderData) {
        // 清除待提交的订单数据
        localStorage.removeItem('pendingOrderData')
        // 跳转到订单确认页面
        router.push('/order/confirm')
      } else {
        // 登录成功后跳转到首页
        router.push('/')
      }
    } else {
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } catch (error) {
    ElMessage.error('登录失败：' + (error.message || '未知错误'))
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = () => {
  router.push('/register')
}

// 页面加载时，如果有记住的用户名，自动填充
const initForm = () => {
  const savedUsername = localStorage.getItem('username')
  if (savedUsername) {
    loginForm.username = savedUsername
    loginForm.rememberMe = true
  }
}

// 初始化表单
initForm()
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.login-header {
  text-align: center;
  margin-bottom: 20px;
}

.login-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.login-form {
  padding: 20px;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-size: 14px;
  color: #666;
}

.el-input {
  width: 100%;
}

.el-link {
  float: right;
}
</style>